package lrscp.lib.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Usage: <code><pre>
 *         LineProcessor proc = new LineProcessor(System.in);
 *         proc.addLineProcessor(new ILineProcessor() {
 *                  public void reachLineEnd() {
 *                  }
 *                  public void processLine(String line) {
 *                  } 
 *         });
 * </pre></code> Add your code to
 * {@link lrscp.lib.io.LineProcessor.ILineProcessor <code>processLine</code>}
 */
public class LineProcessor implements Runnable {
    InputStreamReader isr = null;
    ArrayList<ILineProcessor> mProcessors = new ArrayList<ILineProcessor>();

    Thread readerThread = new Thread(this);

    public interface ILineProcessor {
        /**
         * Add your code to handle each line
         */
        public void processLine(String line);

        public void reachLineEnd();
    }

    public LineProcessor(InputStream in) {
        isr = new InputStreamReader(in);
        readerThread.start();
    }

    public void dispose() {
        readerThread.stop();
    }

    public void addLineProcessor(ILineProcessor processor) {
        synchronized (mProcessors) {
            mProcessors.add(processor);
        }
    }

    public void removeLineProcessor(ILineProcessor processor) {
        synchronized (mProcessors) {
            mProcessors.remove(processor);
        }
    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                synchronized (mProcessors) {
                    for (ILineProcessor processor : mProcessors) {
                        processor.processLine(line);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // notify the end of stream
        synchronized (mProcessors) {
            for (ILineProcessor processor : mProcessors) {
                processor.reachLineEnd();
            }
        }
    }
}